package org.hu.service.impl;


import com.fasterxml.jackson.databind.ObjectMapper;
import org.hu.service.WxLoginService;
import org.hu.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Base64;
import java.util.Map;

@Service
public class WxLoginServiceImpl implements WxLoginService {

    // 将配置文件的appid和secret注入到appId和appSecret中
    @Value("${wx.appid}")
    private String appId;

    @Value("${wx.secret}")
    private String appSecret;

    public String login(String code) {
        String url = String.format(
                "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                appId, appSecret, code);

        RestTemplate restTemplate = new RestTemplate();
        // 1. 用 String 接收原始 JSON
        String json = restTemplate.getForObject(url, String.class);

        // 2. 手动转换为 Map
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> response;
        try {
            response = mapper.readValue(json, Map.class);
        } catch (Exception e) {
            throw new RuntimeException("解析微信响应失败", e);
        }
        if (response.get("openid") != null) {
            String openid = (String) response.get("openid");
            // 可在数据库中查找或保存用户信息
            String username = openid;
            // 生成自定义 token（此处示例为 Base64，推荐 JWT）
            return JwtUtil.generateToken(username);
        } else {
            throw new RuntimeException("登录失败：" + response);
        }
    }

}
